<template>
  <div class="app-container">
    <!-- <textarea ref="editor" v-model="contentValue" :init="init" @change="handChange"></textarea> -->
    <Editor v-model="contentValue" :init="init" :id="props.id" :placeHolder="placeHolder" />
  </div>
</template>
<script setup>
import { ref, onMounted, defineEmits, watch, computed } from "vue";
import tinymce from "tinymce/tinymce";
import { uploadImgPublic } from "@/apis/http";
import { ElMessage } from "element-plus";
// import "tinymce/models/dom"; // 特别注意 tinymce 6.0.0 版本之后必须引入，否则不显示
import "tinymce/themes/silver/theme";
import Editor from "@tinymce/tinymce-vue"; // 引入组件

// 都是富文本插件
import "tinymce/icons/default";
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/wordcount";
// import func from "vue-temp/vue-editor-bridge";
// 以上所有的样式在 node_modules 下面 tinymce 里面的 plugins 都能找到。
const tinymceHtml = ref("");
const init = {
  //初始化数据
  language_url: "/langs/zh-Hans.js", // 引入语言包（该语言包在public下，注意文件名称）
  language: "zh-Hans", // 这里名称根据 zh-Hans.js 里面写的名称而定
  skin_url: "/skins/ui/oxide", // 这里引入的样式
  height: 600, // 限制高度
  plugins: "link lists image code table wordcount", // 富文本插件
  toolbar: [
    "removeformat undo redo tabledelete | copy| cut | bullist numlist | outdent indent | forecolor backcolor | table | image  | fullscreen code| charmap",
    "bold italic blockquote | h2 p  media link | alignleft aligncenter alignright | formatselect| fontsizeselect| styleselect | fontselect",
  ],
  fontsize_formats:
    "8px 10px 12px 14px 16px 18px 20px 22px 24px 26px 28px 30px 32px 34px 36px",
  font_formats:
    "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
  branding: false, // //是否禁用“Powered by TinyMCE”
  menubar: false, //顶部菜单栏显示
  // paste_convert_word_fake_lists: false, // 插入word文档需要该属性
  content_css: "/skins/content/default/content.css", //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
  paste_data_images: true,
  init_instance_callback: (e) => {
    e.on("paste", (evt) => {
      const clipboardData = evt.clipboardData;

      const isImage =
        clipboardData.types.length &&
        clipboardData.types.join("").includes("Files");
      console.log(evt);
      if (!isImage) {
        const hexStrings = parseRtf(evt.clipboardData.getData("text/rtf"));
        // 获取base64图片数据
        const base64Images = hexStrings.map((hexObj) => {
          // console.log(hexObj.hex,8888888888888888)
          return convertHexToBase64(hexObj.hex);
        });
        setTimeout(() => {
          const wordImages = tinymce.activeEditor.dom.doc.querySelectorAll(
            'img[src*="file://"]'
          );
          wordImages.forEach((item, index) => {
            var formData = new FormData();
            var a = base64toBlob(base64Images[index], "imgtype");
            formData.set("file", blobToFile(a, "name1.jpg"));
            // formData.append('file', blobToFile(a,'name1'))
            console.log(blobToFile(a, "name1"));

            uploadImgPublic(formData)
              .then((res) => {
                console.log("wordPic" + JSON.stringify(res));
                if (res.code == 0) {
                  console.log(res.data);
                  item.src = res.data.OSSUrl;
                }
              })
              .catch(() => {
                ElMessage.error("图片插入失败");
              });
          });
        }, 200);
        return;
      }
      const file = clipboardData.files[0];
      if (
        !file ||
        !file.name ||
        !(
          file.name.toLowerCase().indexOf(".png") !== -1 ||
          file.name.toLowerCase().indexOf(".gif") !== -1 ||
          file.name.toLowerCase().indexOf(".jpeg") !== -1 ||
          file.name.toLowerCase().indexOf(".jpg") !== -1
        )
      ) {
        ElMessage.error("您粘贴的不是图片请检查！");
        return;
      }
      if (file.size / 1024 / 1024 > 5) {
        ElMessage.error("上传失败，图片大小请控制在 5M 以内");
        return;
      }
      var formData = new FormData();
      formData.append("file", file);
      uploadImgPublic(formData)
              .then((res) => {
                console.log("wordPic" + JSON.stringify(res));
                if (res.code == 0) {
                  console.log(res.data);
                  item.src = res.data.OSSUrl;
                }
              })
              .catch(() => {
                ElMessage.error("图片插入失败");
              });


    });

  },
  // 图片点击按钮上传回调函数
  images_upload_handler: function (blobInfo, success, failure) {
    const isAccord =
      blobInfo.blob().type === "image/jpeg" ||
      blobInfo.blob().type === "image/png" ||
      blobInfo.blob().type === "image/GIF" ||
      blobInfo.blob().type === "image/jpg" ||
      blobInfo.blob().type === "image/BMP";
    if (blobInfo.blob().size / 1024 / 1024 > 5) {
      ElMessage.error("上传失败，图片大小请控制在 5M 以内");
    } else if (blobInfo.blob().type == isAccord) {
      ElMessage.error("图片格式错误");
    } else {
      let formData = new FormData();
      formData.append("file", blobInfo.blob(), blobInfo.filename());
      uploadImgPublic(formData)
        .then((res) => {
          if (res.code == 0) {
            success(res.data.OSSUrl);
          }

        })
        .catch(() => {
          ElMessage.error("请联系管理员！");
        });
    }
  },
};
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
    default: "",
  },
  menubar: {
    type: [Boolean, String],
    default: "file edit insert view format table tools help",
  },

  height: {
    type: Number,
    default: 600,
  },
  id: {
    type: [String, Number],
    default: "myTinymce",
  },
  placeHolder: {
    type: String,
    default: "myTinymce",
  },
});
const emit = defineEmits(["update:modelValue"]);
const contentValue = computed({
  get() {
    return resetContentSrc(props.modelValue);
  },
  set(value) {
    emit("update:modelValue", resetContentSrc(value));
  },
});
const resetContentSrc = (content) => {
  if (!content) return "";
  const reg = /<img.*?src="(.*?)".*?>;/g;
  if (content.match(reg)) {
    return content.replace(
      /src=(['"])\/upload/gi,
      "src=$1" + import.meta.env.VITE_BASE_URL + "/upload"
    );
  } else {
    return content;
  }
};

onMounted(() => {
   //判断是否加载完，如果出现问题重新生成
  if (window.tinymce) {
  console.log('TinyMCE Editor Loaded Successfully!');
} else {
  tinymce.init({}); // 初始化富文本
  console.log('Failed to Load TinyMCE Editor!');
}
});

function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
  theBlob.name = fileName; // 文件名
  return new File([theBlob], fileName, {
    type: theBlob.type,
    lastModified: Date.now(),
  });
}

/**
 * 将base64编码转换为二进制文件
 */
function base64toBlob(base64, type) {
  console.log(base64, 99999);
  // 将base64转为Unicode规则编码
  let bstr = atob(base64, type),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n); // 转换编码后才可以使用charCodeAt 找到Unicode编码
  }
  return new Blob([u8arr], {
    type,
  });
}

function convertHexToBase64(hexString) {
  return btoa(
    hexString
      .match(/\w{2}/g)
      .map((char) => {
        return String.fromCharCode(parseInt(char, 16));
      })
      .join("")
  );
}
function parseRtf(rtfData) {
  if (!rtfData) {
    return [];
  }
  const regexPictureHeader =
    /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/;
  const regexPicture = new RegExp(
    "(?:(" + regexPictureHeader.source + "))([\\da-fA-F\\s]+)\\}",
    "g"
  );
  const images = rtfData.match(regexPicture);
  const result = [];

  if (images) {
    for (const image of images) {
      let imageType = false;
      if (image.includes("\\pngblip")) {
        imageType = "image/png";
      } else if (image.includes("\\jpegblip")) {
        imageType = "image/jpeg";
      }
      if (imageType) {
        result.push({
          hex: image
            .replace(regexPictureHeader, "")
            .replace(/[^\da-fA-F]/g, ""),
          type: imageType,
        });
      }
    }
  }
  return result;
}
</script>
<style lang="scss" scoped>
.app-container {
  width: 82%;
}
</style>